package com.example.elderlycaresystem.util;

import com.example.elderlycaresystem.properties.JwtProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class JwtTokenUtil {

    private static JwtProperties jwtProperties;

    @Autowired
    public void setJwtProperties(JwtProperties jwtProperties) {
        JwtTokenUtil.jwtProperties = jwtProperties;
    }

    // 生成Token
    public static String generateToken(String userId, String username) {
        Date now = new Date();
        Date expiration = new Date(now.getTime() + jwtProperties.getUserTtl());

        return Jwts.builder()
                .setSubject(userId)
                .claim("username", username)
                .setIssuedAt(now)
                .setExpiration(expiration)
                .signWith(SignatureAlgorithm.HS512, jwtProperties.getUserSecretKey())
                .compact();
    }

    // 验证Token并获取用户ID
    public static String getUserIdFromToken(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(jwtProperties.getUserSecretKey())
                .parseClaimsJws(token)
                .getBody();
        return claims.getSubject();
    }

    // 验证Token是否有效

    public static boolean validateToken(String token) {
        try {
            Jwts.parser().setSigningKey(jwtProperties.getUserSecretKey()).parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}